export function debounce(delay, callback) {
  let lastTime
  return function f(args) {
    clearTimeout(lastTime)
    lastTime = setTimeout(() => {
      callback.apply(this, args)
    }, delay)
  }
}

export function observerDomResize(dom, callback) {
  const MutationObserver = window.MutationObserver
  const observer = new MutationObserver(callback)
  observer.observe(dom, {
    attributes: true,
    attributeFilter: ['style'],
    attributeOldValue: true,
  })
  return observer
}

export function diff(oldArr, newArr) {
  const add = newArr.filter((item) => !oldArr.includes(item))
  const del = oldArr.filter((item) => !newArr.includes(item))
  return { add, del }
}

export function colorCodeToRgb(code) {
  const opacity = code.substring(0, 2)
  const rgb = code.substring(2)
  return [`#${rgb}`, parseInt(opacity, 16) / 255]
}

/**
 * 将数字转换为中文
 * @param num 需要转换得数字
 * @returns
 */
export function numberToChinese(num) {
  let units = ['', '十', '百', '千', '万', '十', '百', '千', '亿']
  let chars = '零一二三四五六七八九'
  let result = ''

  let numStr = num.toString()
  let length = numStr.length

  for (let i = 0; i < length; i++) {
    let digit = parseInt(numStr.charAt(i))

    if (digit !== 0) {
      result += chars.charAt(digit) + units[length - 1 - i]
    } else {
      // 处理连续的零，只保留一个零
      if (result[result.length - 1] !== '零') {
        result += chars.charAt(digit)
      }
    }
  }

  // 处理特殊情况，如果最后一个字符是零，则去除
  if (result[result.length - 1] === '零') {
    result = result.slice(0, -1)
  }

  return result
}
